package com.pml.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Set;
import java.util.TreeSet;

public class OnlineUserList implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener {
    private ServletContext app;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        this.app=servletContextEvent.getServletContext();
        this.app.setAttribute("userList",new TreeSet<String>());
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        Set set=(Set)this.app.getAttribute("userList");
        if (httpSessionBindingEvent.getName().equals("userId")) {
            String userId = (String) httpSessionBindingEvent.getValue();
            set.add(userId);
            this.app.setAttribute("userList",set);
        }


    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        Set set=(Set)this.app.getAttribute("userList");
        if(httpSessionBindingEvent.getName().equals("userId")){
            set.remove(httpSessionBindingEvent.getValue());
            this.app.setAttribute("userList",set);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        Set set=(Set)this.app.getAttribute("userList");
        set.remove(httpSessionEvent.getSession().getAttribute("userId"));
        this.app.setAttribute("userList",set);
    }
}
